package com.sky.task;

import com.sky.dto.OrdersPageQueryDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;

@Slf4j
@Component
public class OrderTask {

    @Autowired
    private OrdersMapper ordersMapper;

    /**
     * 定时任务：取消超时未支付订单
     * <p>
     * 每分钟执行一次
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void orderPayTimeoutTask() {
        log.info("定时任务开始：取消超时未支付订单");
        // 1. 查询超时未支付的订单
        OrdersPageQueryDTO query = new OrdersPageQueryDTO();
        query.setStatus(Orders.PENDING_PAYMENT); // 待付款
        LocalDateTime now = LocalDateTime.now();
        query.setEndTime(now.minusMinutes(15)); // 超过15分钟未支付
        List<Orders> list = ordersMapper.list(query);

        // 2. 超时则关闭订单
        for (Orders order : list) {
            Orders updateQuery = Orders.builder()
                    .id(order.getId())
                    .status(Orders.CANCELLED)
                    .cancelTime(now)
                    .cancelReason("超时未支付")
                    .build();
            ordersMapper.update(updateQuery);
        }
        log.info("定时任务结束：更新未支付订单数量：{}", list.size());
    }

    /**
     * 定时任务：凌晨自动确认派送超时订单
     * <p>
     * 每天凌晨1点执行
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void orderDeliveryTimeoutTask() {
        log.info("定时任务开始：自动确认派送超时订单");
        // 1. 查询派送超时未确认的订单
        OrdersPageQueryDTO query = new OrdersPageQueryDTO();
        query.setStatus(Orders.DELIVERY_IN_PROGRESS); // 派送中
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime startOfDay = now.with(LocalTime.MIN); // 00:00:00
        query.setEndTime(startOfDay); // 昨天未确认的订单
        List<Orders> list = ordersMapper.list(query);

        // 2. 第二天自动确认订单
        for (Orders order : list) {
            Orders updateQuery = Orders.builder()
                    .id(order.getId())
                    .status(Orders.COMPLETED)
                    .deliveryTime(now)
                    .build();
            ordersMapper.update(updateQuery);
        }
        log.info("定时任务结束：自动确认派送超时订单数量：{}", list.size());
    }

}
